<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>
        摄像头查看
    </title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <link rel="stylesheet" href="${pageContext.request.contextPath }/statics/css/main.css" media="all">
    <link rel="stylesheet" href="${pageContext.request.contextPath }/statics/css/bootstrap.css">
    <%--<script type="text/javascript" src="${pageContext.request.contextPath }/statics/lib/loading/okLoading.js"></script>--%>
    <style>
        #add {
            background: url(/statics/images/loginbg1.jpg) no-repeat center center;
        }
    </style>
</head>
<body style="text-align: center">
<div class="x-nav" style="text-align: left;border: none">
            <span class="layui-breadcrumb">
              <a><cite>首页</cite></a>
              <a><cite>车辆管理</cite></a>
              <a><cite>摄像头查看</cite></a>
            </span>
    <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:3px;float:right"
       href="javascript:location.replace(location.href);" title="刷新"><i class="layui-icon"
                                                                        style="line-height:30px">ဂ</i></a>
</div>
<div style="height: 100%;margin-top: -10px" id="add">
    <div class="layui-inline" style="margin: 0 auto">
        <video width="800px" height="450px;" style="background-color: #0C0C0C;"></video>
        <canvas width="450px" height="230px" ></canvas>
        <%--<img src="#" id="view">--%>
        <p style="margin-top: 25px">
            <button id="start" class="layui-btn">打开摄像头</button>
            <button id="snap" class="layui-btn layui-btn-normal" style="display: none;margin-right: 60px">截取图像</button>
            <button id="close" class="layui-btn layui-btn-danger" style="margin-left: 60px">关闭摄像头</button>
        </p>
    </div>
    <div align="center">
        <h1 id="h1" style="color:#EB5526"></h1>
        <h3 id="h3" style="color:#30ADC6"></h3>
    </div>
</div>
<script src="${pageContext.request.contextPath }/statics/lib/layui/layui.js" charset="utf-8"></script>
<script src="${pageContext.request.contextPath }/statics/js/x-layui.js" charset="utf-8"></script>
<script src="${pageContext.request.contextPath }/statics/js/jquery.min.js"></script>
<script>
    var flag = false;
    window.onload = function () {
        var canvas = document.getElementsByTagName('canvas')[0],
            context = canvas.getContext('2d'),
            video = document.getElementsByTagName("video")[0],
            snap = document.getElementById("snap"),
            close = document.getElementById("close"),
            start = document.getElementById("start"),
            MediaStreamTrack;
        start.addEventListener('click', function () {       //打开摄像头
            flag = true
            console.log("打开摄像头——————" + flag)
            startCamera();
            if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                navigator.mediaDevices.getUserMedia({
                    video: true,
                    audio: true
                }).then(function (stream) {
                    MediaStreamTrack = typeof stream.stop === 'function' ? stream : stream.getTracks()[1];
                    // video.src=(window.URL).createObjectURL(stream);
                    try {
                        video.srcObject = stream;
                    } catch (e) {
                        video.src = (window.URL).createObjectURL(stream);
                    }
                    video.play();
                }).catch(function (err) {
                    console.log(err);
                });
            } else if (navigator.getMedia) {
                navigator.getMedia({
                    video: true
                }).then(function (stream) {
                    MediaStreamTrack = stream.getTracks()[1];
                    // video.src=(window.webkitURL).createObjectURL(stream);
                    try {
                        video.srcObject = stream;
                    } catch (e) {
                        video.src = (window.URL).createObjectURL(stream);
                    }
                    video.play();
                }).catch(function (err) {
                    console.log(err);
                });
            }
        });
        //start.click()
        snap.addEventListener('click', function () {        //截取图像
            context.drawImage(video, 0, 0, 450, 230);
            convertCanvasToImage(canvas);
        });
        close.addEventListener('click', function () {       //关闭摄像头
            flag = false;
            console.log("关闭摄像头——————" + flag)
            MediaStreamTrack && MediaStreamTrack.stop();
        });

        function startCamera() {
            var inter = setInterval(function () {
                if (flag) {
                    console.log("自动扫描---")
                    context.drawImage(video, 0, 0, 450, 230);
                    convertCanvasToImage(canvas);
                } else {
                    clearInterval(inter)
                    console.log("再次扫描---")
                }
            }, 5000)
        }
    }


    // Converts canvas to an image
    function convertCanvasToImage(canvas) {
        var statu = 0;
        var licenseplate;
        var str = canvas.toDataURL("image/png");
        var imgData = str.replace("data:image/png;base64,", "");
        // console.log(imgData)
        $.ajax({
            url: "getlicense",
            data: {imgData: imgData},
            type: "post",
            dataType: "json",
            success: function (data) {
                statu = getJsonLength(data);
                $("#h1").html("")
                $("#h3").html("");
                if (statu == 2) {
                    //获取车牌号
                    licenseplate = data.words_result.number
                    exist(licenseplate)
                }
            }
        })
    }

    function getJsonLength(jsonData) {
        var jsonLength = 0;
        for (var item in jsonData) {
            jsonLength++;
        }
        return jsonLength;
    }

    var result = 0; //用来判断车辆进出记录是否存在
    var obj;
    var exist = function (licensePlate) {
        $.ajax({
            url: "/vehicle/exist",
            data: {licensePlate: licensePlate},
            type: "GET",
            dataType: "JSON",
            success: function (data) {
                if (data.data != null) {     //内部
                    select(licensePlate)
                    if (result == 0) {
                        $("#h1").html("欢迎进入智慧小区：" + licensePlate)
                        insert(licensePlate, 2, 1)     //车辆进出记录插入一条内部车辆信息
                    } else {
                        if (obj.statuc == 2) {
                            $("#h1").html("欢迎进入智慧小区：" + licensePlate)
                            update(licensePlate)
                        } else {
                            $("#h1").html("一路平安：" + licensePlate)
                            update(licensePlate)
                        }
                    }
                } else {   //外来
                    select(licensePlate)
                    if (result == 0) {
                        $("#h1").html("欢迎进入智慧小区：" + licensePlate)
                        $("#h3").html("温馨提示：外来车辆，请勿久留！");
                        insert(licensePlate, 1, 1)
                    } else {
                        console.log(obj)
                        if (obj.statuc == 2) {
                            $("#h1").html("欢迎进入智慧小区：" + licensePlate)
                            $("#h3").html("温馨提示：外来车辆，请配合登记！");
                            update(licensePlate)
                        } else {
                            $("#h1").html("一路平安：" + licensePlate)
                            $("#h3").html("温馨提示：外来车辆，请配合登记！");
                            update(licensePlate)
                        }
                    }
                }
            }
        })
    }

    var select = function (licensePlate) {
        $.ajax({
            url: "/license/list",
            data: {licensePlate: licensePlate},
            async: false,//取消异步请求
            type: "GET",
            dataType: "JSON",
            success: function (data) {
                console.log(data)
                result = data.data.records.length
                obj = data.data.records[0]
            }
        })
    }

    var insert = function (licensePlate, interior, statuc) {
        $.ajax({
            url: "/license/add",
            data: {licensePlate: licensePlate, interior: interior, statuc: statuc},
            type: "POST",
            dataType: "JSON",
            success: function (data) {
                console.log("/license/add")
                console.log(data)
            }
        })
    }

    var update = function (licensePlate) {
        $.ajax({
            url: "/license/updatebylicenseplate",
            data: {licensePlate: licensePlate},
            type: "PUT",
            dataType: "json",
            success: function (data) {
                console.log("/license/update")
                console.log(data)
            }
        })
    }


</script>

<script>
    layui.use(['laydate', 'element', 'laypage', 'layer'], function () {
        $ = layui.jquery;//jquery
        laydate = layui.laydate;//日期插件
        lement = layui.element();//面包导航
        laypage = layui.laypage;//分页
        layer = layui.layer;//弹出层
        okLoading.close($);
    });
</script>

</body>
</html>